package com.zyb.warehouse.filter;

import com.alibaba.fastjson.JSON;
import com.zyb.warehouse.common.Result;
import com.zyb.warehouse.utils.WarehouseConstants;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.List;

/**
 * Description:登录过滤器
 */
public class LoginFilter implements Filter {

    private StringRedisTemplate redisTemplate;

    //set方法用来设置redisTemplate
    public void setRedisTemplate(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        //获取请求url接口
        String uri = request.getServletPath();
        //白名单放行
        List<String> uriList = Arrays.asList("/captcha/captchaImage", "/login", "/logout","/product/img-upload");
        if (uriList.contains(uri) || uri.contains("/img/upload")) {
            filterChain.doFilter(request, response);
            return;
        }
        //其它请求都校验token
        //拿到前端归还的token
        String frontToken = request.getHeader(WarehouseConstants.HEADER_TOKEN_NAME);
        //token校验通过,请求放行
        if (StringUtils.hasText(frontToken) && redisTemplate.hasKey(frontToken)) {
            filterChain.doFilter(request, response);
            return;
        }
        //token校验失败,向前端响应失败的Result对象转成的json串
        Result result = Result.err(Result.CODE_ERR_UNLOGINED, "未登录");
        String jsonString = JSON.toJSONString(result);
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.print(jsonString);
        out.flush();
        out.close();
    }
}
